/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import java.awt.Color;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JOptionPane;
import modelo.GestorClientes;
import org.hibernate.HibernateException;
import persistencia.ClientesDAO;
import pojos.Cliente;

/**
 *
 * @author cvenegas
 */
public class PanelClientes extends javax.swing.JPanel {

    private VentanaPrincipal ventanaPpal;
    private JDialogClienteNuevo jDialogClienteNuevo;
    private JDialogClienteEditar jDialogClienteEditar;
    
    private GestorClientes gestor;
    
    private Cliente cliente;
    
    
    private int jComboBox_Clientes_index;
    
    
    private int TODOS = 1, SOLO_UN_CLIENTE = 0;
    /**
     * Creates new form jPanelHistoriaClinica
     */
    public PanelClientes(VentanaPrincipal v) {
        this.ventanaPpal = v;
        initComponents();
        this.addKeyListener();
        gestor = new GestorClientes(this);
    }
    
    /**
     * Añadimos el listener al texfield para poder buscar pulsando enter
     * además de "clickar" en el boton Buscar
     */
    private void addKeyListener(){
        this.jTextField_Clientes_cif.addKeyListener(new KeyAdapter(){
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER){
                    buscar();
                }
            }
        });
    }
    
    /**
     * Muestra un dialogo en el JPanel
     * @param msg texto del mensaje del JOptionPane
     */
    private void mostrarDialogo(String msg) {
        JOptionPane.showMessageDialog(this.getParent(),
            msg, "Hosptital - Historia Clinica", JOptionPane.INFORMATION_MESSAGE);
    }
    
    
    
    private void nuevoCliente() {
        jDialogClienteNuevo = new JDialogClienteNuevo(ventanaPpal, this, true);
        jDialogClienteNuevo.setVisible(true);
        gestor = new GestorClientes(this);
        
    }
    
    private void selectComboBox() {
        jComboBox_Clientes_index = jComboBox_Clientes_cif_todos.getSelectedIndex();
        
        if (jComboBox_Clientes_index == TODOS){
            jTextField_Clientes_cif.setText("");
            jTextField_Clientes_cif.setEnabled(false);
            jTextField_Clientes_cif.setEditable(false);
        }else{
            jTextField_Clientes_cif.setEnabled(true);
            jTextField_Clientes_cif.setEditable(true);
        }
    }
    
    
    private void editar(){
        
        if (jTableClientes.getSelectedRow()== -1){
                JOptionPane.showMessageDialog(this.getParent(),
                                                "Para Editar un Cliente primero debes selecionarlo",
                                                "Editar Cliente - ERP_SGE ",
                                                JOptionPane.INFORMATION_MESSAGE);
        }else{
            
            int row = jTableClientes.getSelectedRow();
            
            try{
                Cliente ClienteTmp = gestor.buscarCliente(row);
                jDialogClienteEditar = new JDialogClienteEditar(ventanaPpal, this, ClienteTmp, true);
                jDialogClienteEditar.setVisible(true);
                
                gestor = new GestorClientes(this);
                
            }catch (HibernateException he){
                mostrarDialogo("No se ha podido Eliminar el Cliente");
            }
            
            
        }
        
        
        
    }
    
    
    private void eliminar(){
        
        if (jTableClientes.getSelectedRow()== -1){
                JOptionPane.showMessageDialog(this.getParent(),
                                                "Para Eliminar un Cliente primero debes selecionarlo",
                                                "Eliminar Cliente - ERP_SGE ",
                                                JOptionPane.INFORMATION_MESSAGE);
        }else{
            
            int row = jTableClientes.getSelectedRow();
            
            try{
                Cliente ClienteTmp = gestor.buscarCliente(row);
                JOptionPane.showConfirmDialog(this, "¿Seguro que quieres eliminar el siguiente Cliente?\n\n" + ClienteTmp.getNombre());
                gestor.eliminar(row);
                mostrarDialogo("Cliente Eliminado Correctamente");
            }catch (HibernateException he){
                mostrarDialogo("No se ha podido Eliminar el Cliente");
            }
            
            
        }
        
    }
    
    
    /**
     * Busca Clientes
     * o bien por un NIF introducido en el formulario
     * o bien todos los Clientes de la base de dats
     * (segun eleccion del comboBox)
     */
    private void buscar(){
        
        gestor.clearList();
        String cif;
        
        if (jComboBox_Clientes_index == TODOS){
            gestor.setlistaClientes();
            gestor.updateTableModel();
        }else{
            if (jTextField_Clientes_cif.getText().equals("")){
                JOptionPane.showMessageDialog(this.getParent(),
                "Introduce NIF del Cliente", "Hospital", JOptionPane.INFORMATION_MESSAGE);
            }else{
                
                cif = jTextField_Clientes_cif.getText();
                if (cif.length() == 9){
                    
                    cliente = gestor.buscarCliente(cif);
                    
                    if (cliente == null){
                        mostrarDialogo("No exite un Cliente con el siguiente NIF: " + cif);
                    }else{
                        gestor.setlistaClientes(cliente);
                        gestor.updateTableModel();
                    }
                }else{
                    mostrarDialogo("Introduce NIF valido (8 nums y 1 letra)\n\nEjemplo: 12345678B");
                }
                
                
            }
        }
        
        
        
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTextField_Clientes_cif = new javax.swing.JTextField();
        jButtonHC_Buscar = new javax.swing.JButton();
        jComboBox_Clientes_cif_todos = new javax.swing.JComboBox();
        jToolBar2 = new javax.swing.JToolBar();
        jButtonClientesRegistrar = new javax.swing.JButton();
        jButtonClientesModificar = new javax.swing.JButton();
        jButtonClientesEliminar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableClientes = new javax.swing.JTable();

        jButtonHC_Buscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/ico_find.png"))); // NOI18N
        jButtonHC_Buscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonHC_BuscarActionPerformed(evt);
            }
        });

        jComboBox_Clientes_cif_todos.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "CIF", "Todos" }));
        jComboBox_Clientes_cif_todos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox_Clientes_cif_todosActionPerformed(evt);
            }
        });

        jToolBar2.setFloatable(false);
        jToolBar2.setRollover(true);

        jButtonClientesRegistrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/ico_new.png"))); // NOI18N
        jButtonClientesRegistrar.setToolTipText("Editar Cliente");
        jButtonClientesRegistrar.setFocusable(false);
        jButtonClientesRegistrar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButtonClientesRegistrar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButtonClientesRegistrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonClientesRegistrarActionPerformed(evt);
            }
        });
        jToolBar2.add(jButtonClientesRegistrar);

        jButtonClientesModificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/ico_edit1.png"))); // NOI18N
        jButtonClientesModificar.setFocusable(false);
        jButtonClientesModificar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButtonClientesModificar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButtonClientesModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonClientesModificarActionPerformed(evt);
            }
        });
        jToolBar2.add(jButtonClientesModificar);

        jButtonClientesEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/ico_bin.png"))); // NOI18N
        jButtonClientesEliminar.setFocusable(false);
        jButtonClientesEliminar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButtonClientesEliminar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButtonClientesEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonClientesEliminarActionPerformed(evt);
            }
        });
        jToolBar2.add(jButtonClientesEliminar);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jLabel1.setText("                         CLIENTES");
        jToolBar2.add(jLabel1);

        jTableClientes.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTableClientes);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jToolBar2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jComboBox_Clientes_cif_todos, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jTextField_Clientes_cif, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButtonHC_Buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jToolBar2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField_Clientes_cif, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jComboBox_Clientes_cif_todos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonHC_Buscar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 115, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 341, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonClientesModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonClientesModificarActionPerformed
        // TODO add your handling code here:
        editar();
    }//GEN-LAST:event_jButtonClientesModificarActionPerformed

    private void jButtonClientesEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonClientesEliminarActionPerformed
        // TODO add your handling code here:
        eliminar();
    }//GEN-LAST:event_jButtonClientesEliminarActionPerformed

    private void jButtonClientesRegistrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonClientesRegistrarActionPerformed
        // TODO add your handling code here:
        nuevoCliente();
    }//GEN-LAST:event_jButtonClientesRegistrarActionPerformed

    private void jButtonHC_BuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonHC_BuscarActionPerformed
        // TODO add your handling code here:
        buscar();
    }//GEN-LAST:event_jButtonHC_BuscarActionPerformed

    private void jComboBox_Clientes_cif_todosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox_Clientes_cif_todosActionPerformed
        // TODO add your handling code here:
        selectComboBox();
    }//GEN-LAST:event_jComboBox_Clientes_cif_todosActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonClientesEliminar;
    private javax.swing.JButton jButtonClientesModificar;
    private javax.swing.JButton jButtonClientesRegistrar;
    private javax.swing.JButton jButtonHC_Buscar;
    private javax.swing.JComboBox jComboBox_Clientes_cif_todos;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    public javax.swing.JTable jTableClientes;
    private javax.swing.JTextField jTextField_Clientes_cif;
    private javax.swing.JToolBar jToolBar2;
    // End of variables declaration//GEN-END:variables
}
